package com.hk.servlet;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hk.model.OnlineMessage;
import com.hk.model.vo.Result;
import com.hk.service.IOnlineMessageService;
import com.hk.service.impl.OnlineMessageServiceImpl;
import com.hk.utils.CharacterEncoding;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: KangWang
 * Date: 2021/5/17 10:20
 * State：Servlet 数据请求转发 控制层
 */
@WebServlet("/message/onlineMessage")
public class OnlineMessageServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        统一字符编码
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        IOnlineMessageService iOnlineMessageService = new OnlineMessageServiceImpl();
        BufferedReader reader = req.getReader();
        Gson gson = new Gson();
        OnlineMessage onlineMessage = gson.fromJson(reader, OnlineMessage.class);
        PrintWriter out = resp.getWriter();
        Result result = new Result();
        if (onlineMessage == null) {
            result.setStatus(0);
            result.setMessage("error");
            String resultJSON = JSONObject.toJSONString(result);
            out.println(resultJSON);
            out.flush();
            out.close();
        }
        int save = iOnlineMessageService.save(onlineMessage);
        if (save < 1) {
            result.setStatus(save);
            result.setMessage("error");
        } else {
            result.setStatus(save);
            result.setMessage("success");
        }
        String resultJSON = JSONObject.toJSONString(result);
        out.println(resultJSON);
        out.flush();
        out.close();

    }
}
